//app.js
wx.cloud.init({
  traceUser: true
})
const db = wx.cloud.database()
const user = db.collection('user')
App({
  onLaunch: function () {
    
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        traceUser: true,
      })
    }

    this.globalData = {}
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })

    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        user.where({
          _openid: res.result.openid
        }).get({
          success: res1 => {
            if (res1.data.length == 0) {
              user.add({
                data: {
                  username: '',
                  avatar: '',
                  sex: 0,
                  oneword: '',
                  tag:[],
                  bgpic: '',
                  createDate: new Date().getTime()
                },
                success: res2 => {
                  // console.log(res2)
                  this.userDataId = res2._id
                  if (this.updateNameCallback) {
                    this.updateNameCallback(res2._id)
                  }
                  if (this.userDataIdCallback) {
                    this.userDataIdCallback(res2._id)
                  }
                }
              })
            } else {
              // console.log(res1.data[0]._id)
              this.userDataId = res1.data[0]._id
              if (this.userDataIdCallback){
                this.userDataIdCallback(res1.data[0]._id)
              }
              if (this.updateNameCallback) {
                this.updateNameCallback(res1.data[0]._id)
              }
            }
          }
        })
      }
    })
  },
  onShow: function () {
    this.mpOpenTime = new Date().getTime()
    wx.cloud.callFunction({
      name: 'isNewMessage'
    }).then(res => {
      // this.showMessageBtn = res.result
      if (this.showMessageBtnCallback){
        this.showMessageBtnCallback(res.result)
      }else{
        this.showMessageBtn = res.result
      }
      
    })
  },
  onHide() {
    wx.cloud.callFunction({
      name: 'updateCloseTime'
    })
  },
  showMessageBtn: false,
  userDataId: '',
  user: {},
  sumCount: {} //【我的海螺】三个数据的记录
})
